const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
const PostComment = require('../models/PostComment');
const { authenticateToken } = require('../middleware/auth');

// 所有路由都需要认证
router.use(authenticateToken);

/**
 * 发布动态
 * POST /posts
 */
router.post('/', async (req, res) => {
  try {
    const { content } = req.body;
    const userId = req.user.userId;
    
    // 参数验证
    if (!content || typeof content !== 'string') {
      return res.status(400).json({
        code: 400,
        message: '动态内容不能为空',
        data: null
      });
    }
    
    if (content.trim().length === 0) {
      return res.status(400).json({
        code: 400,
        message: '动态内容不能为空',
        data: null
      });
    }
    
    if (content.length > 1000) {
      return res.status(400).json({
        code: 400,
        message: '动态内容不能超过1000个字符',
        data: null
      });
    }
    
    const post = await Post.create(userId, content.trim());
    
    res.json({
      code: 200,
      message: '动态发布成功',
      data: post
    });
  } catch (error) {
    console.error('发布动态失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '发布动态失败',
      data: null
    });
  }
});

/**
 * 获取好友动态列表
 * GET /posts/friends
 */
router.get('/friends', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { page = 1, limit = 10 } = req.query;
    
    // 参数验证
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (isNaN(pageNum) || pageNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '页码必须是大于0的整数',
        data: null
      });
    }
    
    if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        code: 400,
        message: '每页数量必须是1-50之间的整数',
        data: null
      });
    }
    
    const result = await Post.getFriendsPosts(userId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取好友动态成功',
      data: result
    });
  } catch (error) {
    console.error('获取好友动态失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取好友动态失败',
      data: null
    });
  }
});

/**
 * 获取用户动态列表
 * GET /posts/user/:userId
 */
router.get('/user/:userId', async (req, res) => {
  try {
    const currentUserId = req.user.userId;
    const { userId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    
    // 参数验证
    if (!userId || typeof userId !== 'string') {
      return res.status(400).json({
        success: false,
        message: '用户ID不能为空'
      });
    }
    
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (isNaN(pageNum) || pageNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '页码必须是大于0的整数',
        data: null
      });
    }
    
    if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        code: 400,
        message: '每页数量必须是1-50之间的整数',
        data: null
      });
    }
    
    const result = await Post.getUserPosts(userId, currentUserId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取用户动态成功',
      data: result
    });
  } catch (error) {
    console.error('获取用户动态失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取用户动态失败',
      data: null
    });
  }
});

/**
 * 获取动态详情
 * GET /posts/:postId
 */
router.get('/:postId', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是有效的数字',
        data: null
      });
    }
    
    const post = await Post.getById(postIdNum, userId);
    
    if (!post) {
      return res.status(404).json({
        code: 404,
        message: '动态不存在',
        data: null
      });
    }
    
    res.json({
      code: 200,
      message: '获取动态详情成功',
      data: post
    });
  } catch (error) {
    console.error('获取动态详情失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取动态详情失败',
      data: null
    });
  }
});

/**
 * 删除动态
 * DELETE /posts/:postId
 */
router.delete('/:postId', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是大于0的整数',
        data: null
      });
    }
    
    await Post.delete(postIdNum, userId);
    
    res.json({
      code: 200,
      message: '删除动态成功',
      data: null
    });
  } catch (error) {
    console.error('删除动态失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '删除动态失败',
      data: null
    });
  }
});

/**
 * 点赞/取消点赞动态
 * POST /posts/:postId/like
 */
router.post('/:postId/like', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是有效的数字',
        data: null
      });
    }
    
    const result = await Post.toggleLike(postIdNum, userId);
    
    res.json({
      code: 200,
      message: result.isLiked ? '点赞成功' : '取消点赞成功',
      data: {
        isLiked: result.isLiked,
        likeCount: result.likeCount
      }
    });
  } catch (error) {
    console.error('点赞操作失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '操作失败',
      data: null
    });
  }
});

/**
 * 获取动态点赞列表
 * GET /posts/:postId/likes
 */
router.get('/:postId/likes', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是有效的数字',
        data: null
      });
    }
    
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (isNaN(pageNum) || pageNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '页码必须是大于0的整数',
        data: null
      });
    }
    
    if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        code: 400,
        message: '每页数量必须是1-50之间的整数',
        data: null
      });
    }
    
    const result = await Post.getLikes(postIdNum, userId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取点赞列表成功',
      data: result
    });
  } catch (error) {
    console.error('获取点赞列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取点赞列表失败',
      data: null
    });
  }
});

/**
 * 发表评论
 * POST /posts/:postId/comments
 */
router.post('/:postId/comments', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    const { content, parentId } = req.body;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是有效的数字',
        data: null
      });
    }
    
    if (!content || typeof content !== 'string') {
      return res.status(400).json({
        code: 400,
        message: '评论内容不能为空',
        data: null
      });
    }
    
    if (content.trim().length === 0) {
      return res.status(400).json({
        code: 400,
        message: '评论内容不能为空',
        data: null
      });
    }
    
    if (content.length > 500) {
      return res.status(400).json({
        code: 400,
        message: '评论内容不能超过500个字符',
        data: null
      });
    }
    
    let parentIdNum = null;
    if (parentId) {
      parentIdNum = parseInt(parentId);
      if (isNaN(parentIdNum) || parentIdNum < 1) {
        return res.status(400).json({
          code: 400,
          message: '父评论ID必须是有效的数字',
          data: null
        });
      }
    }
    
    const comment = await PostComment.create(postIdNum, userId, content.trim(), parentIdNum);
    
    res.json({
      code: 200,
      message: '评论发表成功',
      data: comment
    });
  } catch (error) {
    console.error('发表评论失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '发表评论失败',
      data: null
    });
  }
});

/**
 * 获取动态评论列表
 * GET /posts/:postId/comments
 */
router.get('/:postId/comments', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { postId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    // 参数验证
    const postIdNum = parseInt(postId);
    if (isNaN(postIdNum) || postIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '动态ID必须是有效的数字',
        data: null
      });
    }
    
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (isNaN(pageNum) || pageNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '页码必须是大于0的整数',
        data: null
      });
    }
    
    if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        code: 400,
        message: '每页数量必须是1-50之间的整数',
        data: null
      });
    }
    
    const result = await PostComment.getCommentsByPostId(postIdNum, userId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取评论列表成功',
      data: result
    });
  } catch (error) {
    console.error('获取评论列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取评论列表失败',
      data: null
    });
  }
});

/**
 * 获取评论回复列表
 * GET /posts/comments/:commentId/replies
 */
router.get('/comments/:commentId/replies', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { commentId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    // 参数验证
    const commentIdNum = parseInt(commentId);
    if (isNaN(commentIdNum) || commentIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '用户ID必须是有效的数字',
        data: null
      });
    }
    
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    if (isNaN(pageNum) || pageNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '页码必须是大于0的整数',
        data: null
      });
    }
    
    if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        code: 400,
        message: '每页数量必须是1-50之间的整数',
        data: null
      });
    }
    
    const result = await PostComment.getReplies(commentIdNum, userId, pageNum, limitNum);
    
    res.json({
      code: 200,
      message: '获取回复列表成功',
      data: result
    });
  } catch (error) {
    console.error('获取回复列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取回复列表失败',
      data: null
    });
  }
});

/**
 * 删除评论
 * DELETE /posts/comments/:commentId
 */
router.delete('/comments/:commentId', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { commentId } = req.params;
    
    // 参数验证
    const commentIdNum = parseInt(commentId);
    if (isNaN(commentIdNum) || commentIdNum < 1) {
      return res.status(400).json({
        code: 400,
        message: '评论ID必须是有效的数字',
        data: null
      });
    }
    
    await PostComment.delete(commentIdNum, userId);
    
    res.json({
      code: 200,
      message: '评论删除成功',
      data: null
    });
  } catch (error) {
    console.error('删除评论失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '删除评论失败',
      data: null
    });
  }
});

module.exports = router;